package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单的方法
     * */
    @Scheduled(cron = "0 * * * * ?")//每一分钟执行一次
    public void processOutTimeOrder(){
        log.info("定时处理超时订单:{}", LocalDateTime.now());
        //获取当前时间减去十五分钟
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        //select * from orders where status = 未支付 and order_time <(当前时间-15min)
        List<Orders> list = orderMapper.getStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, localDateTime);
        if(!list.isEmpty()){
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orderMapper.update(orders);
            }
        }
    }
    /**
     * 处理一直处于派送中的订单
     * */
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨一点执行一次
    public void processDeliveryOrder(){
        log.info("定时处理一直处于派送中的订单：{}",LocalDateTime.now());
        LocalDateTime localDateTime = LocalDateTime.now().plusHours(-1);
        List<Orders> list = orderMapper.getStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        for (Orders orders : list) {
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        }
    }
}
